/*
 * Using Ajax to client campaign
 */
if (typeof HCM !== 'object') var HCM = {};

HCM.getCampaign = function(el) {
    var $root_el = $(el);
    var client_select;
    var campaign_select;

    this.onReady = function() {
        client_select = $root_el.find('#ddl_clientkey');
        campaign_select = $root_el.find('#ddl_campaignkey');
        init();

        client_select.change(function(){
            campaign_select.empty();
            getCampaigns();
        });
    };

    var getCampaigns = function() {
        if (client_select.val() == 0) {
            campaign_select.empty();
        } else {
            $.get('/get/campaign',
            {
                cid: client_select.val()
            }, getCampaignSuccess, 'text');
        }
    };

    var init = function() {
        getCampaigns();
    }

    var getCampaignSuccess = function(data) {
        // this can be changed to $.parseJSON(data)
        var jsonData = eval('(' + data + ')');
        for (var i = 0; i < jsonData.length; i++) {
            campaign_select.append("<option value='" +  jsonData[i]['CampaignKey'] + "'>" +
                jsonData[i]['CampaignName'] + "</option>");
        }
    };
}

$(function() {
    $('.form').each(function () {
        new HCM.getCampaign(this).onReady();
    });
});